package com.ruoyi.system.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.IOUtil;
import com.ruoyi.common.utils.MapPro;
import com.ruoyi.common.utils.RedisService;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SupplyUser;
import com.ruoyi.system.mapper.SupplyUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.SupplierMapper;
import com.ruoyi.system.domain.Supplier;
import com.ruoyi.system.service.ISupplierService;

/**
 * 供货商Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-28
 */
@Service
public class SupplierServiceImpl implements ISupplierService 
{
    @Autowired
    private SupplierMapper supplierMapper;
    @Autowired
    private SupplyUserMapper supplyUserMapper;
    @Autowired
    RedisService redis;

    /**
     * 获取供货商的统计数据
     * @param supplier
     * @return
     */
    public AjaxResult getCountData(Supplier supplier){
        //查询供货商总数
        long sid = supplier.getId();
        String month = IOUtil.getdate("yyyy-MM");
        String day7 = IOUtil.getAfterTimeByDay(IOUtil.getdate("yyyy-MM-dd"), -8);
        //总体数据
        Map<String,Object> countData = supplierMapper.getCountData(sid,month);
        //近7天数据
        List<Map<String,Object>> list = supplierMapper.getWeeklyData(sid,day7);

        JSONObject data = new JSONObject();
        data.put("countData",countData);
        data.put("list",list);
        return AjaxResult.success(data);
    }

    /**
     * 绑定客户
     *
     * @param supplier
     * @param code
     * @return
     */
    @Override
    public AjaxResult bindCustomer(Supplier supplier, String code) {
        int res = 0;
        //如果万能验证码，直接绑定公司1
        if(code.equals(Constants.UNIVERSAL_CODE)){
            res = supplierMapper.bindSupplier(supplier.getId(), 1);
        }else{

            //从redis中获取验证码
            String key = supplier.getPhone() + "#" + code;
            //查看redis中是否有验证码
            if(redis.getVal(key)==null){return AjaxResult.error("验证码无效或已过期，请重新获取！");}
            long companyId = Long.parseLong(redis.getStrVal(key));//要绑定的公司的ID

            //更新状态，完成绑定
            res = supplierMapper.bindSupplier(supplier.getId(), companyId);
        }


        return AjaxResult.success(res);
    }

    /**
     * 查询供货商
     * 
     * @param id 供货商主键
     * @return 供货商
     */
    @Override
    public Supplier selectSupplierById(Long id)
    {
        return supplierMapper.selectSupplierById(id);
    }

    /**
     * 查询供货商列表
     * 
     * @param supplier 供货商
     * @return 供货商
     */
    @Override
    public List<Supplier> selectSupplierList(Supplier supplier)
    {
        return supplierMapper.selectSupplierList(supplier);
    }

    /**
     * 新增供货商
     * 
     * @param supplier 供货商
     * @return 结果
     */
    @Override
    public AjaxResult insertSupplier(Supplier supplier)
    {
        //判断名称是否重复
        if(StringUtils.isNotEmpty(supplier.getSuppliName())){

            Supplier s = new Supplier();
            s.setSuppliName(supplier.getSuppliName());
            List<Supplier> list = supplierMapper.selectSupplierList(s);
            if(list!=null && list.size()>0){
                return AjaxResult.error("供货商名称重复，请重新输入！");
            }
        }
        //插入供货商
        //处理密码加密
        String pwd = supplier.getPwd();
        supplier.setPwd(IOUtil.MD5(pwd));
        int res = supplierMapper.insertSupplier(supplier);
        if(res>0){
            //插入supply_uer
            SupplyUser su = new SupplyUser();
            su.setPwd(supplier.getPwd());
            su.setSupplyId(supplier.getId());
            su.setName(supplier.getName());
            su.setPhone(supplier.getPhone());
            su.setSupplyName(supplier.getSuppliName());
            su.setType("1");
            res=supplyUserMapper.insertSupplyUser(su);
        }

        return AjaxResult.success(res);
    }

    /**
     * 修改供货商
     * 
     * @param supplier 供货商
     * @return 结果
     */
    @Override
    public int updateSupplier(Supplier supplier)
    {
        return supplierMapper.updateSupplier(supplier);
    }

    /**
     * 批量删除供货商
     * 
     * @param ids 需要删除的供货商主键
     * @return 结果
     */
    @Override
    public AjaxResult deleteSupplierByIds(Long[] ids)
    {
        StringBuffer idsStr = new StringBuffer("(");
        for (int i = 0; i < ids.length; i++) {
            idsStr.append(ids[i]);
            if (i < ids.length - 1) {
                idsStr.append(",");
            }
        }
        idsStr.append(")");

        //判断供应商是否已经绑定客户，如果绑定了客户，则不能删除
        List<MapPro> mapProList = supplierMapper.getCSList(0,0,idsStr.toString());
        if(mapProList!=null && mapProList.size()>0){
            return AjaxResult.error("该供应商已经绑定客户，不能删除！");
        }

        return AjaxResult.int2Ajax(supplierMapper.deleteSupplierByIds(ids));
    }

    /**
     * 删除供货商信息
     * 
     * @param id 供货商主键
     * @return 结果
     */
    @Override
    public AjaxResult deleteSupplierById(Long id)
    {
        //判断供应商是否已经绑定客户，如果绑定了客户，则不能删除
        List<MapPro> mapProList = supplierMapper.getCSList(0,id,null);
        if(mapProList!=null && mapProList.size()>0){
            return AjaxResult.error("该供应商已经绑定客户，不能删除！");
        }

        return AjaxResult.int2Ajax(supplierMapper.deleteSupplierById(id));
    }
}
